#include <iostream>
#include <vector>
#include <pthread.h>
#include <string>
#include <unistd.h>
#include <sys/types.h>
using namespace std;

int ticket = 50;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

struct threadData
{
    string threadName;
    threadData(int num)
    {
        threadName = "thread" + to_string(num);
    }
};

void *getTicket(void *args)
{
    threadData *data = (threadData *)args;
    while (true)
    {
        pthread_mutex_lock(&lock);
        if (ticket > 0)
        {
            usleep(10);//增加抢票的过程使得现象明显
            printf("%s get ticket sucess！ remain ticket: %d\n", data->threadName.c_str(), --ticket);
            pthread_mutex_unlock(&lock);
        }
        else
        {
            printf("%s quit!\n", data->threadName.c_str());
            pthread_mutex_unlock(&lock);
            break;
        }
        usleep(10);//抢完票的后序工作
    }
    return (void *)0;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < 3; i++)
    {
        pthread_t tid;
        threadData *data = new threadData(i);
        pthread_create(&tid, nullptr, getTicket, data);
        tids.push_back(tid);
    }

    for (auto tid : tids)
    {
        void *retData;
        pthread_join(tid, &retData);
    }

    return 0;
}